package client

import (
	"encoding/json"
	"fastdp-ops/pkg/server/api/models"
	pb "fastdp-ops/proto/machine"
	"fmt"
	"github.com/jedib0t/go-pretty/v6/table"
	"github.com/spf13/cobra"
	"os"
	"strconv"
	"strings"

	. "fastdp-ops/pkg/server/api/middleware"
)

// HostCmd 主机管理命令
var HostCmd = &cobra.Command{
	Use:     "host",
	Short:   "fastdp-ops 主机管理",
	Long:    "管理 fastdp-ops 注册的主机信息，包括查看、删除等操作",
	Example: "查看所有主机信息: fastdp-ops host -l\n删除指定主机: fastdp-ops host -d 192.168.1.100",
	Args:    cobra.NoArgs,
	Run: func(cmd *cobra.Command, args []string) {
		InitZapLogger()
		defer Logger.Sync()
		// 初始化数据库
		SqlLiteInit()

		// 获取命令行参数
		list, _ := cmd.Flags().GetBool("list")
		deleteIP, _ := cmd.Flags().GetString("delete")

		switch {
		case list:
			listHosts()
		case deleteIP != "":
			deleteHost(deleteIP)
		default:
			_ = cmd.Help()
		}
	},
}

// listHosts 列出所有主机信息
func listHosts() {
	var machineList []models.Machines
	if err := DB.Order("machine_ip asc").Find(&machineList).Error; err != nil {
		fmt.Printf("❌ 查询主机列表失败: %v\n", err)
		os.Exit(1)
	}

	if len(machineList) == 0 {
		fmt.Println("ℹ️ 当前没有注册的主机")
		return
	}

	// 创建表格
	t := table.NewWriter()
	t.SetOutputMirror(os.Stdout)
	t.SetStyle(table.StyleLight)
	t.Style().Options.SeparateRows = true

	// 表头
	t.AppendHeader(table.Row{
		"ID", "IP地址", "主机名", "操作系统", "状态",
		"CPU核心", "内存(GB)", "磁盘(GB)", "最后更新",
	})

	// 表格内容
	for i, m := range machineList {
		// 格式化磁盘信息
		diskInfo := "无数据"
		if len(m.Disks) > 0 {
			var diskInfos []*pb.DiskInfo
			if err := json.Unmarshal(m.Disks, &diskInfos); err != nil {
				diskInfos = []*pb.DiskInfo{}
			}
			var totalGB int
			for _, disk := range diskInfos {
				totalGB += int(disk.TotalGb)
			}
			diskInfo = strconv.Itoa(totalGB)
		}

		// 格式化状态
		status := "❌ 离线"
		if m.Status == 1 {
			status = "✅ 在线"
		}
		
		t.AppendRow(table.Row{
			i+1,
			m.MachineIP,
			m.Hostname,
			fmt.Sprintf("%s/%s", m.OSName, m.Arch),
			status,
			m.CPUCores,
			m.MemoryTotal,
			diskInfo,
			m.UpdatedAt.Format("2006-01-02 15:04"),
		})
	}

	// 表格脚注
	t.AppendFooter(table.Row{"", "", "", "", "", "", "", "总计", len(machineList)})

	fmt.Println("\n📋 注册主机列表")
	t.Render()
	fmt.Printf("共 %d 台主机\n", len(machineList))
}

// deleteHost 删除指定主机
func deleteHost(ip string) {
	// 验证IP格式
	ip = strings.TrimSpace(ip)
	if ip == "" {
		fmt.Println("❌ 必须指定要删除的主机IP地址")
		os.Exit(1)
	}

	var machine models.Machines
	result := DB.Where("machine_ip = ?", ip).First(&machine)

	if result.Error != nil {
		fmt.Printf("❌ 未找到主机: %s\n", ip)
		os.Exit(1)
	}

	// 确认删除
	fmt.Printf("⚠️ 确认删除主机 [%s]%s 吗? (y/N): ", machine.MachineIP, machine.Hostname)
	var confirm string
	fmt.Scanln(&confirm)

	if strings.ToLower(confirm) != "y" {
		fmt.Println("操作已取消")
		return
	}

	// 执行删除
	if err := DB.Delete(&machine).Error; err != nil {
		fmt.Printf("❌ 删除主机失败: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("✅ 主机 %s (%s) 已成功删除\n", machine.MachineIP, machine.Hostname)
}

func init() {
	// 注册命令行参数
	HostCmd.Flags().BoolP("list", "l", false, "列出所有主机信息")
	HostCmd.Flags().StringP("delete", "d", "", "删除指定主机（按IP地址）")
}
